package cn.genmer.test.security.utils;

import com.github.dozermapper.core.Mapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 对象映射工具类
 *
 * @author dngzs
 * @date 2022年03月23日15:39:04
 */
@Component
public class DozerBeanUtils {

    @Autowired
    private Mapper mapper;

    /**
     * 克隆
     *
     * @param base
     * @param <P>
     * @return
     */
    public <P> P clone(P base) {
        if (base == null) {
            return null;
        } else {
            return (P) mapper.map(base, base.getClass());
        }
    }

    /**
     * 克隆了表
     *
     * @param baseList
     * @param <P>
     * @return
     */
    public <P> List<P> cloneList(List<P> baseList) {
        if (baseList == null) {
            return null;
        } else {
            List<P> targetList = new ArrayList<>();
            for (P p : baseList) {
                targetList.add(clone(p));
            }
            return targetList;
        }
    }

    /**
     * 转换
     *
     * @param base
     * @param target
     * @param <V>
     * @param <P>
     * @return
     */
    public <V, P> P convert(V base, Class<P> target) {
        if (base == null) {
            return null;
        } else {
            return mapper.map(base, target);
        }
    }

    /**
     * 转换
     *
     * @param base
     * @param target
     * @param <V>
     * @param <P>
     * @return
     */
    public <V, P> P convert(V base, P target) {
        if (base != null) {
            mapper.map(base, target);
            return target;
        }
        return target;
    }

    /**
     * 转换list
     *
     * @param baseList
     * @param target
     * @param <V>
     * @param <P>
     * @return
     */
    public <V, P> List<P> convertList(List<V> baseList, Class<P> target) {
        List<P> targetList = new ArrayList<>();
        if (CollectionUtils.isEmpty(baseList)) {
            return new ArrayList<>();
        } else {
            for (V vo : baseList) {
                targetList.add(convert(vo, target));
            }
            return targetList;
        }
    }
}
